﻿/*
 *  Copyright (c) 2014 UTUO WMFL, All rights reserved.
 *  http://www.wmfl.cn
 *
 *  @verson 1.0
 *  @author rguanghui(<a href="mailto:rguanghui.stupid@gmail.com">rguanghui.stupid@gmail.com</a>)
 *  @description some text for waiting write
 */
(function($){
  $.fn.extend({
    
    imagePreview: function(configs){
      //经过图片路径文本框时显示预览图片
          var img = $("<img>");
          $(this).on("mouseover", function(e){
              $(this).parent().css({
                  "position": "relative"
              });
              img.attr("src", $(this).val());
              img.css({
                  "position": "absolute",
                  "top": 0,
                  "left": "100%",
                  "maxWidth": "200px"
              });
              img.appendTo($(this).parent());
          }).on("mouseout", function(e){
              img.remove();
          });
    },
    
    //消息通知(固定在浏览器顶部的居中文本)， type类型有: success/info/warning/danger（默认info）， msg: 弹出消息（默认无）
    alertMsg: function(configs)
    {
      var defaults = {
          type: "info",
          msg: ""
      };
      configs = $.extend({}, defaults, configs);
      var oMsg = $("<div class='alert alert-"+configs.type+" alert-dismissable'>"+configs.msg+"<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;</button></div>").appendTo(document.body);
      oMsg.css({
        position: "fixed",
        zIndex: "9999",
        top: "50px",
        maxWidth: "500px",
        overflow: "hidden",
        left: "50%",
        WebkitTransform: "translateX(-50%)",
        display: "none",
        borderRadius: "0 0 4px 4px"
      });
      oMsg.slideDown(600).delay(2000).slideUp(600, function(){oMsg.remove()});
    },
    
    //读取本地图片并预览， IE10+以上浏览器才可支持
    //参数说明——type: 支持类型（默认图片）， maxSize: 大小限制(kb 默认200kb)， maxNum: 数量限制（默认为5）
    uploadPreview: function(configs)
    {
      var defaults = {
          type: ["png", "jpg", "gif", "jpeg"],
          maxSize: 200,
          maxNum: 5
      };
      configs = $.extend({}, defaults, configs);
      
      //jQ重写了event，需要重新设置一下
      jQuery.event.props.push("dataTransfer");
      //创建文件域以模拟点击
      var oParent = this.parent();
      this.file = $("<input type='file' name='pic' multiple/>").appendTo(oParent);
      this.file.hide();
      var oFile = this.file;
      
      //创建结果显示层
      var showImage = $("<div></div>").appendTo(oParent);
      showImage.css("margin", "10px 0");
      var oImage = null;
      
      //进度条
      var progressHandle = $("<div id='progress' class='progress' style='display:none;'></div>").appendTo(showImage);
      var progressBar = $("<div class='progress-bar'></div>").appendTo(progressHandle);
      
      //模拟点击
      this.bind("click", function(){
        oFile.trigger("click");
      });
      
      //拖拽支持
      this.bind("dragover", dragOver).bind("drop", selectFile);
  
      //监听文件域
      this.file.on("change", selectFile);
      
      //拖拽进来发送数据
      function dragOver(ev)
      {
        ev.stopPropagation();
        ev.preventDefault();
        ev.dataTransfer.dropEffect = "copy";
      };
      
      //判断文件格式以及大小
      function selectFile(ev)
      {
        ev.stopPropagation();
        ev.preventDefault(); //阻止一些默认行为什么的。。
        
        var files = ev.target.files || ev.dataTransfer.files; //获取选择或者拖拽过来的文件
        
        //文件选择过多
        if(files.length > configs.maxNum)
        {
          $().alertMsg({type: "info", msg: "上传的文件个数请不要大于"+configs.maxNum+"张"});
          return;
        }
        
        var truetype = []; //正确格式文件
        var falseType = []; //错误格式文件
        var falseSize = [];  //错误大小文件
        $.each(files, function(index, theFile){
          //文件格式大小的判断
          if(!theFile.type.match("^image/"+configs.type.join("|")))
          {
            falseType.push(theFile.name);
            return;
          }
          else if(theFile.size > configs.maxSize*1000)
          {
            falseSize.push(theFile.name);
            return;
          }
          else
          {
            truetype.push(theFile);
          }
        });
        
        if(falseType.length != 0){
          $().alertMsg({type: "danger", msg: "<strong>"+falseType.join("，")+"</strong> 不是图片文件"});
        }
        if(falseSize.length != 0){
          $().alertMsg({type: "danger", msg: "<strong>"+falseSize.join("，")+"</strong> 过大，请不要超过" + configs.maxSize + "kb大小"});
        }

        readerFile(truetype);
        
        return false;
      };
      
      //读取文件
      function readerFile(files)
      {
        for(var i=0; f=files[i]; i++){

          //xmlhttprequest 2.0 请求
          var fd = new FormData();
          fd.append("pic", f);
          fd.append("info", "some text");
          console.log(f);
          var xhr = new XMLHttpRequest();
          xhr.upload.addEventListener("progress", uploadProgress, false);
          xhr.upload.addEventListener("load", uploadComplete, false);
          //xhr.addEventListener("error", uploadFailed, false);
          //xhr.addEventListener("abort", uploadCanceled, false);

          xhr.open("post", configs.url, true);
          xhr.send(fd);
          xhr.onreadystatechange = function(){
            if(xhr.readyState === 4 && xhr.status === 200){
              console.log(xhr.responseText);
            }
          }
          
          
          //使用JQ
          /*
          $.ajax({
            url: configs.url,
            type: "POST",
            data: fd,
            processData: false,
            contentType: false,
            success: function(data){alert(data);}
          })
          */
          
          //读取
          
          reader = new FileReader();
          reader.onload = (function(file)
          {
            return function(ev){
              oImage = $("<image src=''/>").appendTo(showImage);
              oImage.attr("src", ev.target.result);
              oImage.css("width", "200");
            }
          })(f);

          reader.readAsDataURL(f);
          
        }
      };
      
      //upload progress
      function uploadProgress(ev)
      {
        if(ev.lengthComputable){
          var percentComplete = Math.round((ev.loaded / ev.total) * 100);
        }else{
          //console.log("unable");
        }
        if(percentComplete <= 100){
          progressHandle.show();
          progressBar.css({width: percentComplete+"%"});
        }
      }
      
      //upload complete
      function uploadComplete()
      {
        $().alertMsg({type: "success", msg: "上传成功"});
        progressHandle.hide();
      }
    }
  });
})(jQuery);


//给所有表单进行表单验证，根据data-loading-txt,data-ajax-url, 进行ajax提交
$(function(){
  $(".form-horizontal").Validform({
    tiptype: 3,
    datatype: {
      "phone" : /^13[0-9]{9}$|14[0-9]{9}|15[0-9]{9}$|17[0-9]{9}$|18[0-9]{9}$/
    },
    callback:function(form){
      var _this = $(form).find("button[data-loading-txt]"); 
      var beforeCallback = $(_this).attr("data-before-callback");
      var afterCallback = $(_this).attr("data-after-callback"); 
      var loadingGifUrl = "http://simlib.sinaapp.com/newwmfl/images/wmfl-loading-black.gif",
        ajaxUrl = $(_this).attr("data-ajax-url"),
        tip = $(_this).parent().find("span");
      
      if(tip){
        tip.remove();
      };
      
      var oSpan = $("<span><img src=" + loadingGifUrl + " />" + $(_this).attr("data-loading-txt") + "</span>").appendTo($(_this).parent());
      
      $(_this).attr("disabled", true);
      beforeCallback && eval(beforeCallback+"();");
      $.post(ajaxUrl, $(".form-horizontal").serialize(), function(data){
        
        if(data.error == 1){
          oSpan.html("<span class='tip tip-danger'>"+data.msg+"</span>")
        }else if(data.error == 0){
          oSpan.html("<span class='tip tip-success'>"+data.msg+"</span>");
        }
        $(_this).removeAttr("disabled");
        afterCallback && eval(afterCallback+"(data);");
      }, "json");
      return false;
    }
  });
});

/*class中含有.actionds执行操作，删除，恢复，彻底删除
**data-action-id 确定操作的数据
**data-action-txt 操作时提示的文字
**data-action-url 操作的地址
**data-action-delete 是否是彻底删除
*/
$(function(){
  $("table").delegate(".actionds", "click", function(){
    var actionUrl = $(this).attr("data-action-url"),//执行的URL
      actionId = $(this).attr("data-action-id"),//执行的id
      actionTxt = $(this).attr("data-action-txt"),//执行动作时的提示文字
      actionDel = $(this).attr("data-action-delete"),//是否是彻底删除按钮
      actionStatus = $(this).attr("data-action-status"),//设置用户状态用
      loadingGifUrl = "http://simlib.sinaapp.com/newwmfl/images/wmfl-loading-black.gif",//loading gif 地址
      tip = $(this).parent().find("span"),
      _this = this;
    
    if(actionDel){
      if(!window.confirm("彻底删除后无法恢复，确定要删除么？")){
        return;
      };
    };
    
    if(tip){
      tip.remove();
    };
    
    $(this).attr("disabled", true);
    
    var oSpan = $("<span style='position:absolute' class='tip tip-info'><img src=" + loadingGifUrl + ">" +actionTxt+ "</span>").appendTo($(this).parent());
    
    $.post(actionUrl, {id: actionId}, function(data){
      if(data.error == 0){
        
        oSpan.html(data.msg);
        setTimeout(function(){
          $(_this).parent().parent().fadeOut(500);
          $(_this).parents("no-hidden").show();
        }, 1500);
        
      }else{
        oSpan.removeClass("tip-info").addClass("tip-danger");
        oSpan.html(data.msg);
        $(_this).removeAttr("disabled");
      }
      
    }, "json");
    
  });
})


/*class中含有.action-status执行更改状态操作
**data-action-id 确定操作的数据
**data-action-txt 操作时提示的文字
**data-action-url 操作的地址
*/
$(function(){
  $(".action-status").click(function(){
    var actionUrl = $(this).attr("data-action-url"),//执行的URL
      actionId = $(this).attr("data-action-id"),//执行的id
      actionTxt = $(this).attr("data-action-txt"),//执行动作时的提示文字
      actionStatus = $(this).attr("data-action-status"),//设置用户状态用
      actionStatusTxt = $(this).attr("data-action-status-txt").split(" "), //更改状态时的替换文字
      loadingGifUrl = "http://simlib.sinaapp.com/newwmfl/images/wmfl-loading-black.gif",//loading gif 地址
      tip = $(this).parent().find("span"),
      _this = this;
    
    if(tip){
      tip.remove();
    };
    
    $(this).attr("disabled", true);
    
    var oSpan = $("<span style='position:absolute' class='tip tip-info'><img src=" + loadingGifUrl + " /> " +actionTxt+ "</span>").appendTo($(this).parent());
    
    $.post(actionUrl, {id: actionId, status: actionStatus}, function(data){
      
      if(data.error == 0){
        oSpan.html(data.msg).delay(1000).fadeOut(400);
        
        if(parseInt(actionStatus)){
          $(_this).html(actionStatusTxt[0]);
          $(_this).parent().siblings(".status").html(actionStatusTxt[1]);
          $(_this).attr("data-action-status", "0");
        }else{
          $(_this).html(actionStatusTxt[1]);
          $(_this).parent().siblings(".status").html(actionStatusTxt[0]);
          $(_this).attr("data-action-status", "1");
        }
        
      }else{
        oSpan.removeClass("tip-info").addClass("tip-danger");
        oSpan.html(data.msg);
        $(_this).removeAttr("disabled");
      }
      $(_this).removeAttr("disabled");
      
    }, "json");
    
  });
});


/*
 * 本地存储图片，加快网页加载速度。 
 * 也可以存储其他文件。待研究。
 * itemName 设置本地存储时的键名
 * url 需要存储的图片的路径
 * expirationTime 设置过期时间
 * holdTime 设置保存时间长
 * isBackground 是作为背景用，还是图片用
 */

(function( window ){
  
  "use strict";
  
  var storageImage = function(obj, itemName, holdTime, isBackground ){
    this.obj = obj;
    this.itemName = itemName;
    this.holdTime = holdTime;
    this.isBackground = isBackground || false;
    this.image = new Image();
    this.init();
  };
  
  storageImage.prototype = {

    storage: function( todaysDate ) {

      var canvas = document.createElement( "canvas" ),
        contxt = canvas.getContext( "2d" );
      
      //设置canvas和图片的宽高一样
      canvas.width = this.image.width;
      canvas.height = this.image.height;
      
      contxt.drawImage( this.image, 0, 0, this.image.width, this.image.height );
      
      var storaged = {};
      storaged.url = canvas.toDataURL("image/png"),
      storaged.date = todaysDate;
      
      //保存到本地中，因为存储有5M的大小限制，所以这里使用try catch 会更好
      try {
        localStorage.setItem( this.itemName, JSON.stringify( storaged ) );
      } catch(e) {
        console.log(e);
      }
      
      this.isBackgound ? ( this.obj.style.background = this.image.src ) : this.obj.setAttribute( "src", this.image.src );
      
    },
    
    storagePrepare: function() {
      
      var date = new Date(),
      todaysDate = ( date.getMonth()+1 ).toString() + date.getDate().toString();
    
      if( localStorage.getItem( this.itemName ) ) {
        
        var item = JSON.parse( localStorage.getItem( this.itemName ) );
        
        if( (item.date+this.holdTime) < todaysDate ) {
          
          this.storage( todaysDate );
          
        } else {
          
          this.isBackgound ? ( this.obj.style.background = item.url ) : this.obj.setAttribute( "src", item.url );
          
        }
        
        
      } else {
        
        this.storage( todaysDate );
        
      }
    },
    
    init: function() {
      var _this = this;
      this.image.src = this.obj.getAttribute( "data-src" );
      this.image.addEventListener("load", function() {
        _this.storagePrepare();
      }, false);
    }
  };
  
  if( typeof define === "function" && define.amd ) {
    define( storageImage );
  } else {
    window.storageImage = storageImage;
  }
  
})( window )